import os

import requests

from setting import SPEECH_CLIENT, MONGODB, TL_DATA, TL_URL, VOICE, CHAT_PATH
from uuid import uuid4


def get_file_content(filePath):
	with open(f"{filePath}.pcm", 'rb') as fp:
		return fp.read()


def audio2text(file_path):
	res = SPEECH_CLIENT.asr(get_file_content(file_path), 'pcm', 16000, {
		'dev_pid': 1536,
	})

	Q = res.get("result")[0]
	return Q


def text2audio(A):
	result = SPEECH_CLIENT.synthesis(A, 'zh', 1, VOICE)
	filename = f"{uuid4()}.mp3"
	filepath = os.path.join(CHAT_PATH, filename)

	if not isinstance(result, dict):
		with open(filepath, 'wb') as f:
			f.write(result)

	return filename


def my_nlp_lowB(Q, toy_id=0):
	# 语音点播 NLP
	# Q - 我想听小毛驴 请播放小毛驴
	if "我想听" in Q or "请播放" in Q:
		content_list = MONGODB.content.find({})
		for content in content_list:
			if content.get("title") in Q:
				return {"music": content.get("music"), "from_user": "ai"}

	# toy 主动发起对话请求
	if "发消息" in Q or "聊天" in Q:
		# 检索toy的通讯录 friend_list - friend_remark - friend_nick
		# friend_id -> friend_type
		# return {
		# 	"from_user": friend_id,
		# 	"chat": filename, # 合成一个语音提示 可以按消息建给friend_remark发消息了
		# 	"friend_type": app / toy
		# }
		pass

	A = go2tuling(Q, toy_id)
	filename = text2audio(A)
	return {"chat": filename, "from_user": "ai"}


def go2tuling(Q, toy_id):
	TL_DATA["perception"]["inputText"]["text"] = Q
	TL_DATA["userInfo"]["userId"] = toy_id
	res = requests.post(TL_URL, json=TL_DATA)
	res_dict = res.json()

	return res_dict.get("results")[0].get("values").get("text")
